
let bip39 = require('../utils/bitcoinTool/bip39.js');

let tool = require('../utils/bitcoinTool/tool.min.js');

let bit = require('../utils/bitcoinTool/bit.min.js')
let CryptoJs = tool.cryptoJs
let Buffer = tool.buffer.Buffer;
let hdkey = tool.hdkey;
let util = tool.util;
let Tx = tool.Tx;
let HDkey = tool.HDkey;
let bitcoin = bit.bitcoin;
let bs58check = bit.bs58check;
let Secp256k1 = bit.secp256k1;
let bitcoinjsMessage = bit.bitmessage; 
let http = require('../utils/httpHelper.js')
let chance = require('../utils/chancenet.js')
 class Wallet{
   constructor(){
     this.mnemonic = bip39.generateMnemonic()
     this.ETHNET = "m/44'/60'/0'/0/0"
     this.BTCNET = "m/44'/0'/0'/0/0"
     let NETWORK = chance.NETWORK;
    // let NETWORK = 'testnet'
     if (NETWORK == 'testnet'){
       this.NET = bitcoin.networks.testnet//测试网
       this.PrivateWIF = 'ef'
     }else if(NETWORK=='mainnet'){
       this.NET = bitcoin.networks.bitcoin//真网
       this.PrivateWIF = '80'
     }
    // 测试网：network 'ef' + key + '01'; 真网：bitcoin 80+ key + 01
   }
   productWallet(mnemonic) {//生成钱包
     mnemonic = mnemonic || this.mnemonic
     var seed = bip39.mnemonicToSeed(mnemonic);
     var hdWallet = hdkey.fromMasterSeed(seed);
     return hdWallet;
   }
   addreETH(hdWallet) {//生成eth地址
     //var key1 = hdWallet.derivePath("m/44'/60'/0'/0/0")
     var key1 = hdWallet.derivePath(this.ETHNET)
     var address1 = util.pubToAddress(key1._hdkey._publicKey, true)
     address1 = util.toChecksumAddress(address1.toString('hex'))
     return address1
   }
   addreBTC(hdWallet) {//生成BTC地址
     var keyBtc = hdWallet.derivePath(this.BTCNET);
     var publickey = keyBtc._hdkey._publicKey
     var addressBtc = this.getAddress(publickey)
     return addressBtc
   }
   getAddress(public1) {//获取地址
     //var NET = this.NET
    var  network = this.NET;
    return bitcoin.address.toBase58Check(bitcoin.crypto.hash160(public1), network.pubKeyHash)//ripemd160算法，base58转码转换成base58编码
   }
   ImportPrivatekey(privatekey){//导入私钥
     //var network = bitcoin.networks.bitcoin
     var network = this.NET;
    //测试网：this.NET 'ef' key '01';真网：bitcoin 80 key 01
     var privateWif = this.PrivateWIF 
     
     var key1 = Buffer.from(privateWif + privatekey + '01', 'hex')
     var wif = bs58check.encode(key1)
     //console.log('是：' + wif)
     var keyPair = bitcoin.ECPair.fromWIF(wif, network) // 导入私钥
     return keyPair
   }
   expressMessage(hdWallet){//eth数字签名
    //var hdWallet = this.productWallet(mnemonic);
    //var key1 = hdWallet.derivePath("m/44'/60'/0'/0/0")
     var key1 = hdWallet.derivePath(this.ETHNET)
    var writeMessage = 'deadbeaf';//明文消息；
    var privateETC = key1._hdkey._privateKey//私钥
    var tMess = util.addHexPrefix(writeMessage)
    var msgHash = util.hashPersonalMessage(Buffer.from(writeMessage, 'hex'))//哈希运算，文件摘要
    var messH = msgHash.toString('hex');
    //debugger
    //console.log('msg:' + messH)
    var signAddress = util.ecsign(util.toBuffer(msgHash), Buffer.from(privateETC, 'hex'))//私钥加密，数字签名，
    var trSign = util.addHexPrefix(signAddress.r.toString('hex') + signAddress.s.toString('hex') + util.toBuffer(signAddress.v).toString('hex'));//合并操作
    return trSign
  }
   signatureBTCMess(hdWallet,privateKey){//btc签名
      var privateBTC  =''
      // var network = bitcoin.networks.bitcoin
      var network = this.NET
      var message = '123456'
      if(hdWallet){
        //测试网：this.NET 'ef' +key+ '01';真网：bitcoin 80+ key+ 01
        //var hdWallet = this.productWallet(mnemonic);
        if(hdWallet.derivePath){
          //var keyBtc = hdWallet.derivePath("m/44'/0'/0'/0/0")
          var keyBtc = hdWallet.derivePath(this.BTCNET)
          privateBTC = keyBtc._hdkey._privateKey
        } else if (hdWallet.derive){
          //var keyBtc = hdWallet.derive("m/44'/0'/0'/0/0")
          var keyBtc = hdWallet.derive(this.BTCNET)
          privateBTC = keyBtc._privateKey
        }
      }
      if(privateKey){
        privateBTC = privateKey
      }else{
        privateBTC = privateBTC.toString('hex')
      }
      //console.log('私钥：'+privateBTC);
      var key1 = Buffer.from(this.PrivateWIF + privateBTC + '01', 'hex')
      var wif = bs58check.encode(key1)
      //console.log('是：' + wif)
      var keyPair = bitcoin.ECPair.fromWIF(wif, network) // 导入私钥
      var privateK = keyPair.d.toBuffer(32)
      var decoded = bs58check.decode(wif)
      var signature = bitcoinjsMessage.sign(message, privateK, keyPair.compressed)
      signature = signature.toString('base64');
      //console.log('比特币:' + signature)
      return signature;
   }
  encryption(pswd, wallet) {//AES钱包加密
     var key = CryptoJs.enc.Utf8.parse(pswd)
     var encryptedData = CryptoJs.AES.encrypt(wallet, key, {
       mode: CryptoJs.mode.ECB,
       padding: CryptoJs.pad.Pkcs7
     });
     encryptedData = encryptedData.ciphertext.toString();
     return encryptedData;
   }
   MD5jiami(val){//md5加密
     return CryptoJs.MD5(val).toString()
   }
   decode(pswd,wallet,flag) {//AES解密钱包；
     var key = CryptoJs.enc.Utf8.parse(pswd);
     var encryptedHexStr = CryptoJs.enc.Hex.parse(wallet);
     var encryptedBase64Str = CryptoJs.enc.Base64.stringify(encryptedHexStr);
     var decryptedData = CryptoJs.AES.decrypt(encryptedBase64Str, key, {
       mode: CryptoJs.mode.ECB,
       padding: CryptoJs.pad.Pkcs7
     });
     var decryptedStr = decryptedData.toString(CryptoJs.enc.Utf8);
     if(flag){
       return decryptedStr
     }else{
       var hdwallet = HDkey.fromJSON(JSON.parse(decryptedStr));
       return hdwallet;
     }
     
   }

   rawData(txParams,hdwallet){//eth交易
    //console.log(txParams)
    //debugger
     var tx = new Tx(txParams)
     //var key1 = hdwallet.derive("m/44'/60'/0'/0/0")
     var key1 = hdwallet.derive(this.ETHNET)
     var privateKey = key1._privateKey;
     privateKey = privateKey.toString('hex')
     tx.sign(Buffer.from(privateKey, 'hex'))
     const serializedTx = tx.serialize()
     var raw = '0x' + serializedTx.toString('hex')                              
     return raw;
  }
   rawBTCDHash(hdWallet){//btc交易
     //var network = bitcoin.networks.bitcoin
     var network = this.NET;
    //  var keyBtc = hdWallet.derive("m/44'/0'/0'/0/0")
     var keyBtc = hdWallet.derive(this.BTCNET)
     var privateBTC = keyBtc._privateKey.toString('hex')
     //console.log('私钥'+privateBTC)

     var key1 = Buffer.from(this.PrivateWIF + privateBTC + '01', 'hex')
     var wif = bs58check.encode(key1)
     //console.log('wif:'+wif)
     return { txb: new bitcoin.TransactionBuilder(network), sender: new bitcoin.ECPair.fromWIF(wif, network)};
  }
  post(url,data,callback,failer){
    var lang = wx.getStorageSync('lang')
    if(!failer){
      wx.showLoading({
        title: lang == "en" ? 'loading...' : '加载中...'
      })
    }
    http.post(url,data,function(res){
     
      if (res.code == "200") {
        wx.hideLoading()
        callback && callback(res)
      } else {
         console.log(res)
          wx.hideLoading()
          failer && failer(res)
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading() 
          if (!failer &&res.message !="Unauthorized"){
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 500
            })
          }
         
      }
    },function(err){
      console.log(err)
      wx.hideLoading()
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading() 
      wx.showToast({
        title: err.errMsg,
        icon: 'none',
        duration: 2000
      })
    })
  }
 }
 
let wallet = new Wallet()
module.exports = wallet